package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGeneratorUtil;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author luoxiaohei
 * @date 2025-05-24
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

    /**
     * 入住申请,保留入住表单
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCheckInForm(CheckInApplyDto dto) {
        //0.分别取出四个dto
        CheckInElderDto elderDto = dto.getCheckInElderDto();
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        List<ElderFamilyDto> familyDtoList = dto.getElderFamilyDtoList();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();

        //1.判断老人是否已经入住了
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, elderDto.getIdCardNo());
        //根据身份证号查出来老人
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
        //如果已经入住就抛异常
        if (elder != null && elder.getStatus() == 1) {
            throw new BaseException("老人已经入住了!");
        }
        //如果没有入住,更新床位信息,先把床位占了
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        String bedNumber = bed.getBedNumber();
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //2.更新或者新增老人
        elder = updateOrInsertElder(elder, bedId, bedNumber, elderDto);

        //3.新增入住信息
        CheckIn checkIn = insertCheckInWithFamily(elder, familyDtoList, checkInConfigDto);

        //4.新增入住配置信息
        insertCheckInConfig(checkInConfigDto, checkIn.getId());

        //5.新增合同信息
        insertContract(checkInContractDto, elder, checkIn);

    }

    /**
     * 新增合同信息
     * @param checkInContractDto
     * @param elder
     * @param checkIn
     */
    private void insertContract(CheckInContractDto checkInContractDto, Elder elder, CheckIn checkIn) {
        //新建一个合同实体类
        Contract contract = new Contract();
        //为contract赋值
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkIn.getStartDate());
        contract.setEndDate(checkIn.getEndDate());
        contract.setStatus(1);
        contract.setSortOrder(0);
        //生成合同编号并赋值
        String contractNumber = CodeGeneratorUtil.generateContractNumber();
        contract.setContractNumber(contractNumber);
        //存入contract表中
        contractMapper.insert(contract);
    }

    /**
     * 新增入住配置信息
     * @param checkInConfigDto
     * @param checkInId
     */
    private void insertCheckInConfig(CheckInConfigDto checkInConfigDto, Long checkInId) {
        //新建一个入住配置实体类
        CheckInConfig checkInConfig = new CheckInConfig();
        //为实体类赋值
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfig.setSortOrder(0);
        //存入check_in_config表中
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住表
     * @param elder
     * @param familyDtoList
     * @param checkInConfigDto
     * @return
     */
    private CheckIn insertCheckInWithFamily(Elder elder, List<ElderFamilyDto> familyDtoList, CheckInConfigDto checkInConfigDto) {
        //新建一个入住表实体类
        CheckIn checkIn = new CheckIn();
        //对需要的字段赋值
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setSortOrder(0);
        checkIn.setRemark(JSON.toJSONString(familyDtoList));
        //保存的进check_in表里面
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增或者更新老人信息
     * @param elder
     * @param bedId
     * @param bedNumber
     * @param elderDto
     * @return
     */
    private Elder updateOrInsertElder(Elder elder, Long bedId, String bedNumber, CheckInElderDto elderDto) {
        //如果能查到老人,就更新老人信息
        if (elder != null ) {
            elder.setBedId(bedId);
            elder.setBedNumber(bedNumber);
            elder.setStatus(1);
            elderMapper.updateById(elder);
        }
        //查不到老人则新增一个老人
        elder = new Elder();
        BeanUtils.copyProperties(elderDto, elder);
        elder.setBedId(bedId);
        elder.setBedNumber(bedNumber);
        elder.setStatus(1);
        elderMapper.insert(elder);
        return elder;
    }

    /**
     * 根据入住信息id查询详细信息
     *
     * @param checkInId
     * @return
     */
    @Override
    public CheckInDetailVo getDetailByCheckInId(Long checkInId) {
        //0.构建返回的Vo对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //1.根据checkInId查询入住信息
        CheckIn checkIn = baseMapper.selectById(checkInId);
        //2.查询并填入checkInElderVo
        CheckInElderVo checkInElderVo = getElderVo(checkIn.getElderId());
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //3.查询并填入家属信息
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        //4.查询并填入入住配置信息
        CheckInConfigVo checkInConfigVo = getCheckInConfigVo(checkIn);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //5.查询并填入合同信息
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(contractLambdaQueryWrapper);
        checkInDetailVo.setContract(contract);
        //6.返回Vo
        return checkInDetailVo;
    }

    private CheckInConfigVo getCheckInConfigVo(CheckIn checkIn) {
        LambdaQueryWrapper<CheckInConfig> checkInConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        checkInConfigLambdaQueryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigLambdaQueryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        return checkInConfigVo;
    }

    private CheckInElderVo getElderVo(Long elderId) {
        //2.1根据入住信息中的老人id查询老人信息
        Elder elder = elderMapper.selectById(elderId);
        //2.2计算年龄
        LocalDate birthday = LocalDate.parse(elder.getBirthday(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        int age = Period.between(birthday, LocalDate.now()).getYears();
        //2.3存入vo中
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(age);
        return checkInElderVo;
    }

}
